import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { View, Text, Image, Button } from '@tarojs/components';
import Taro, { useDidShow, useRouter } from '@tarojs/taro';
import utils from '@/utils/index';
import { sourceUrl } from '@/config';
import Imagelocation from '@/components/Imagelocation';
import pTakeOut from '@/mainSubPack/images/shopInfo/takeOut.png';
import pShop from '@/mainSubPack/images/shopInfo/shop.png';
import pPay from '@/mainSubPack/images/shopInfo/pay.png';
import pPhone from '@/mainSubPack/images/shopInfo/phone.png';
import CommentChoice from '@/components/Comment/List/choice';
import CommentImagePreview from '@/components/Comment/ImagePreview/index';
import ProductTitle from '@/components/product/ProductTitle';

import './index.scss';

const BusinessHour = ({ businessStatus, businessHoursType, orgBusinessHourList = [] }) => {
  let hourDom = null;
  let dayDom = null;
  if (businessHoursType == 1) {
    hourDom = <Text className="hour">24小时</Text>;
    dayDom = <Text className="day">每天</Text>;
  } else if (businessHoursType == 2) {
    hourDom =
      orgBusinessHourList[0].dayList &&
      orgBusinessHourList[0].dayList.length > 0 &&
      orgBusinessHourList[0].dayList.map((hour, idx) => (
        <Text className="hour" key={'hour' + idx}>
          {hour}
        </Text>
      ));
    dayDom = <Text className="day">每天</Text>;
  } else if (businessHoursType == 3) {
    if (orgBusinessHourList.length == 1) {
      hourDom =
        orgBusinessHourList[0].dayList &&
        orgBusinessHourList[0].dayList.length > 0 &&
        orgBusinessHourList[0].dayList.map((hour, idx) => (
          <Text className="hour" key={'hour' + idx}>
            {hour}
          </Text>
        ));
      dayDom = (
        <Text className="day">
          {orgBusinessHourList[0].weekdayList ? orgBusinessHourList[0].weekdayList.join('、') : ''}
        </Text>
      );
    } else {
      dayDom = orgBusinessHourList.map((item, idx) => {
        let hDom = item.dayList.map((hour, didx) => (
          <Text className="txt txth" key={'hour' + didx}>
            {hour}
          </Text>
        ));
        return (
          <View className="oneline" key={'bline' + idx}>
            <Text className="txt">{item.weekdayList ? item.weekdayList.join('、') : ''}</Text>
            {hDom}
          </View>
        );
      });
    }
  }
  return (
    <View className="businessHour">
      <View className="hourLine">
        <Text className="title">{businessStatus ? '营业中' : '休息中'}</Text>
        <Text className="colDivider"></Text>
        {hourDom}
      </View>
      <View className="dayLine">{dayDom}</View>
    </View>
  );
};

const Theme = ({ themeGoods = [], dispatch }) => {
  return (
    <View className="themeContent">
      {themeGoods.length > 0 &&
        themeGoods.slice(0, 10).map((good, index) => (
          <View
            className="goodInfo"
            key={'theme' + good.id + '_' + index}
            onClick={() => utils.goGoodDetail(good, dispatch)}
          >
            <View className="goodIcon">
              <Image
                className="gIcon"
                src={good.url.indexOf('http') === 0 ? good.url : sourceUrl + good.url}
              />
            </View>
            <View className="goodBase">
              {/* <Text className="goodName">{good.title}</Text> */}
              <ProductTitle product={good} />

              <Text className="goodPrice customePageStyle">¥{good.price}</Text>
              <Text className="goodSale">已售卖{good.saleNum || 0}件</Text>
            </View>
          </View>
        ))}
    </View>
  );
};

const ShopInfoPage = ({ dispatch, shopBaseInfo = {}, recProductList = [] }) => {
  const [curLocation, setCurLocation] = useState(null);
  const [commentCount, setCommentCount] = useState(0);
  const [needRefreash, setNeedRefreash] = useState(0);
  const router = useRouter();
  const { params = {} } = router;
  const orgId = params.orgId;

  useDidShow(() => {
    let pages = Taro.getCurrentPages();
    let curPage = pages[pages.length - 1];
    if (curPage.data.needRefreash) {
      curPage.setData({ needRefreash: false });
      setNeedRefreash(Math.random());
    }
  });

  const handleLoad = (res) => {
    setCommentCount(res);
  };

  const getLocation = async () => {
    let localLocation = utils.getLocalEffectLocation();
    if (localLocation) {
      const { latitude, longitude } = localLocation;
      setCurLocation({ latitude, longitude });
    } else {
      Taro.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        timeout: 5000,
        success: (res) => {
          const { latitude, longitude } = res;
          const timeStamp = new Date().getTime();
          setCurLocation({ latitude, longitude });
          utils.setLocalStorage('location', { latitude, longitude, timeStamp });
        },
        fail: () => {
          setCurLocation({ latitude: undefined, longitude: undefined });
        },
      });
    }
  };

  const showMap = () => {
    if (shopBaseInfo.latitude && shopBaseInfo.longtitude) {
      Taro.openLocation({
        latitude: parseFloat(shopBaseInfo.latitude),
        longitude: parseFloat(shopBaseInfo.longtitude),
        scale: 15,
        name: shopBaseInfo.name || '',
        address: shopBaseInfo.address || '',
      });
    } else {
      Taro.showToast({
        title: `${shopBaseInfo.name}未配置店铺地址`,
        duration: 1000,
        icon: 'none',
      });
    }
  };
  const getShopBaseInfo = () => {
    dispatch({
      type: 'otherApi/getLocalOrgDetail',
      payload: { orgId, longtitude: curLocation.longitude, latitude: curLocation.latitude },
    });
  };

  const getRecommendProduct = () => {
    dispatch({
      type: 'productList/getRecommendByOrg',
      payload: { orgId, page: 1, pageSize: 20, sort: 1 },
    });
  };

  const handleConcat = () => {
    if (shopBaseInfo.mobile && shopBaseInfo.mobile.length > 0) {
      Taro.makePhoneCall({
        phoneNumber: shopBaseInfo.mobile,
      });
    }
  };

  const goShoppingMall = () => {
    let url =
      '/mainSubPack/shoppingMall/index?orgId=' +
      shopBaseInfo.objShop.orgId +
      '&merchantId=' +
      shopBaseInfo.merchantId;
    Taro.navigateTo({
      url,
    });
  };

  const goShopPay = () => {
    if (!utils.getToken()) {
      Taro.navigateTo({
        url: '/pages/other/login/index',
      });
      return;
    }
    let url =
      '/mainSubPack/shopPay/index?orgId=' +
      shopBaseInfo.id +
      '&orgName=' +
      shopBaseInfo.name +
      '&merchantId=' +
      shopBaseInfo.merchantId;
    Taro.navigateTo({
      url,
    });
  };

  const goShopComment = () => {
    if (!utils.getToken()) {
      Taro.navigateTo({
        url: '/pages/other/login/index',
      });
      return;
    }
    if (shopBaseInfo.id) {
      Taro.navigateTo({
        url: `/orderSubPack/submitComment/index?id=${shopBaseInfo.id}&name=${shopBaseInfo.name}&appId=thjs_locallife_org`,
      });
    }
  };

  const goTakeOutShop = () => {
    let url =
      '/mainSubPack/takeOutShop/index?orgId=' +
      shopBaseInfo.objTakeOut.orgId +
      '&merchantId=' +
      shopBaseInfo.merchantId;
    Taro.navigateTo({
      url,
    });
  };

  useEffect(() => {
    getLocation();
  }, []);

  useEffect(() => {
    curLocation && getShopBaseInfo();
  }, [curLocation]);

  useEffect(() => {
    if (shopBaseInfo.objShop && shopBaseInfo.objShop.support) {
      getRecommendProduct();
    }
  }, [shopBaseInfo]);

  return (
    <View className="ShopInfoPage">
      <CommentImagePreview />
      <View className="shopBaseInfo">
        <View className="shopName">{shopBaseInfo.name}</View>
        {shopBaseInfo.notice && <View className="shopNotice">商户公告：{shopBaseInfo.notice}</View>}
        {shopBaseInfo.imageList && shopBaseInfo.imageList.length > 0 && (
          <View className="shopPics">
            {shopBaseInfo.imageList.map((pic, idx) => (
              <Imagelocation className="pic" src={pic} type="shopPhoto" key={'shopPic' + idx} />
            ))}
          </View>
        )}
        {shopBaseInfo.objTakeOut &&
          (shopBaseInfo.objTakeOut.support || shopBaseInfo.objPay.support) && (
            <>
              <BusinessHour
                businessStatus={shopBaseInfo.businessStatus}
                businessHoursType={shopBaseInfo.businessHoursType}
                orgBusinessHourList={shopBaseInfo.orgBusinessHourList}
              />
              <View className="rowDivider"></View>
              <View className="shopLocation">
                <View className="left" onClick={showMap}>
                  <View className="address">{shopBaseInfo.address}</View>
                  <View className="distance">距你{shopBaseInfo.distance}km</View>
                </View>
                <View className="right">
                  <View className="phone" onClick={handleConcat}>
                    <Image className="phoneIcon" src={pPhone} />
                    <Text className="phoneTxt">电话</Text>
                  </View>
                </View>
              </View>
            </>
          )}
        {shopBaseInfo.objShop &&
          (shopBaseInfo.objShop.support ||
            shopBaseInfo.objTakeOut.support ||
            shopBaseInfo.objPay.support) && (
            <View className="funcDoor">
              {shopBaseInfo.objPay.support && (
                <View className="ditem" onClick={goShopPay}>
                  <Image className="dicon" src={pPay} />
                  <Text className="dtxt">买单</Text>
                </View>
              )}
              {shopBaseInfo.objTakeOut.support && (
                <View className="ditem" onClick={goTakeOutShop}>
                  <Image className="dicon" src={pTakeOut} />
                  <Text className="dtxt">外卖</Text>
                </View>
              )}
              {shopBaseInfo.objShop.support && (
                <View className="ditem" onClick={goShoppingMall}>
                  <Image className="dicon" src={pShop} />
                  <Text className="dtxt">商城</Text>
                </View>
              )}
            </View>
          )}
      </View>
      {shopBaseInfo.objPay && shopBaseInfo.objShop.support && (
        <View className="recProduct">
          <View className="recTitle">推荐商品</View>
          <Theme themeGoods={recProductList} dispatch={dispatch} />
        </View>
      )}
      {/*{shopBaseInfo.objPay && shopBaseInfo.objPay.support && (*/}
      {/*  <View className="fixPay">*/}
      {/*    <Button className="btn-red" onClick={goShopPay}>*/}
      {/*      太湖买单*/}
      {/*    </Button>*/}
      {/*  </View>*/}
      {/*)}*/}
      <View className="commentChoiceBox">
        <View className="commentChoiceContent">
          <View className="commentChoiceTitle">精选评价({commentCount})</View>
          <CommentChoice
            topicId={orgId}
            type={2}
            showRate
            appId="thjs_locallife_org"
            reload={needRefreash}
            onLoad={handleLoad}
          ></CommentChoice>
        </View>
      </View>
      <View className="fixPay">
        <Button className="btn-red customePageBackgroundStyle" onClick={goShopComment}>
          评价门店
        </Button>
      </View>
    </View>
  );
};

export default connect(({ productList, otherApi }) => ({
  recProductList: productList.recShopProductList,
  shopBaseInfo: otherApi.shopBaseInfo,
}))(ShopInfoPage);
